package com.example.ddd.domain.model;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 订单实体 - 聚合根
 */
public class Order {
    private String id;
    private String customerId;
    private LocalDateTime createTime;
    private OrderStatus status;
    private List<OrderItem> items;
    private double totalAmount;
    
    public Order(String customerId) {
        this.id = UUID.randomUUID().toString();
        this.customerId = customerId;
        this.createTime = LocalDateTime.now();
        this.status = OrderStatus.CREATED;
        this.items = new ArrayList<>();
        this.totalAmount = 0.0;
    }
    
    // 添加订单项
    public void addItem(String productId, int quantity, double price) {
        OrderItem item = new OrderItem(productId, quantity, price);
        this.items.add(item);
        this.totalAmount += item.getAmount();
    }
    
    // 提交订单
    public void submit() {
        if (this.status != OrderStatus.CREATED) {
            throw new IllegalStateException("订单状态不允许提交");
        }
        if (this.items.isEmpty()) {
            throw new IllegalStateException("订单不能为空");
        }
        this.status = OrderStatus.SUBMITTED;
    }
    
    // 支付订单
    public void pay() {
        if (this.status != OrderStatus.SUBMITTED) {
            throw new IllegalStateException("订单状态不允许支付");
        }
        this.status = OrderStatus.PAID;
    }
    
    // 取消订单
    public void cancel() {
        if (this.status == OrderStatus.PAID || this.status == OrderStatus.CANCELLED) {
            throw new IllegalStateException("订单状态不允许取消");
        }
        this.status = OrderStatus.CANCELLED;
    }
    
    // Getters and setters
    public String getId() {
        return id;
    }
    
    public String getCustomerId() {
        return customerId;
    }
    
    public LocalDateTime getCreateTime() {
        return createTime;
    }
    
    public OrderStatus getStatus() {
        return status;
    }
    
    public List<OrderItem> getItems() {
        return new ArrayList<>(items);
    }
    
    public double getTotalAmount() {
        return totalAmount;
    }
}